package com.wyu.servlet;

import com.wyu.dao.YGDao;
import com.wyu.dao.YGDaoImpl;
import com.wyu.pojo.YG;
import com.wyu.util.DesUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/UpdatePassword")
public class UpdatePassword extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //接受新旧密码
        String oldpassword = request.getParameter("oldpassword");
        String newpassword = request.getParameter("newpassword");
        String confirm = request.getParameter("confirm");
        System.out.println("输入的新密码是"+newpassword);

        try {
            DesUtil des = new DesUtil("Java");
            String newmm = des.encrypt(newpassword);//des加密
            String oldpassword1 =des.encrypt(oldpassword);
            YGDao dao = new YGDaoImpl();
            HttpSession session = request.getSession();
            String password = ((YG) request.getSession().getAttribute("yg")).getMm();
            int yuangonghao = ((YG) request.getSession().getAttribute("yg")).getYgh();
            if (!(oldpassword1.equals(password))){
                session.setAttribute("password","原密码错误");
                response.sendRedirect("xgmm.jsp");
                return;
            }
            if ((newpassword.equals(oldpassword))) {
                session.setAttribute("password", "新密码与最近使用的密码相同,请使用其他密码");
                //保留在原界面
                response.sendRedirect("xgmm.jsp");
                return;
            }
            if (!(newpassword.equals(confirm))) {
                //保留在原界面
                response.sendRedirect("xgmm.jsp");
                session.setAttribute("password", "提示：两次输入的密码不一致");
                return;
            }
            if (dao.updatePassword(yuangonghao, newmm) != 0) {
                //修改成功，保留在原界面
                response.sendRedirect("xgmm.jsp");
                session.setAttribute("password", "成功修改密码,重新登录后生效");
                return;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
